package com.wibo.account;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
import com.wibo.common.Constants;
import com.wibo.common.FileDbHelper;
import com.wibo.common.UserItem;
import com.wibo.common.Utility;
import com.wibo.common.WeiboItem;
import com.wibo.service.IWeiboService;
import com.wibo.service.IWeiboServiceCallback;
import com.wibo.service.WeiboService;

import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class WiboMainActivity extends Activity implements OnClickListener,
		OnGestureListener, OnTouchListener, OnScrollListener, OnItemClickListener {

	public static final String TAG = "WiboMainActivity";
	
	
	public static final String USER_INFO = "USER_INFO";
	public static final String LOGIN_NAME = "LOGIN_NAME";
	public static final String USER_NAME = "USER_NAME";
	public static final String USER_ID = "USER_ID";
	public static final String IMAGE_QUALITY = "IMAGE_QUALITY";
	public static final String LOADING_IMAGE_PATH = "LOADING_IMAGE_PATH";
	public static final String SEND_WEIBO_BACKGRROUND = "SEND_WEIBO_BACKGRROUND";
	
	private static Weibo mWeibo = null;
	private static OAuthConstant mAuthConstant = null;
	protected FileDbHelper mDbHelper = null;
	private ProgressBar mProgressBar = null;
	private CUserManager mUserManager = null;
	private boolean mbRunning = false;
	
	private PullToRefreshListView mWeiboListView = null;
	private RelativeLayout mHeadLayout = null;
	private View mLvfooter = null;
	private ProgressBar mFooterPro = null;
	private WeiboListItemAdapter mWeiboListItemAdapter = null;
	private ArrayList<WeiboItem> mItemDataList;

	Thread mThread = null;

	private static ProgressDialog mWaitDialog = null;

	private static final int GET_TOKEN = 1;
	private static final int SHOW_WEIBO = 2;
	private static final int SHOW_WEIBO_ERROR = 3;
	private static final int SHOW_WEIBO_TOP = 4;
	private static final int SHOW_WEIBO_BUTTOM = 5;
	private static final int SHOW_WEIBO_FROM_DATABASE = 6;
	private static final int REFRESH_LIST = 7;
	

	public static final String LOADING_PIC = "loading";
	GestureDetector mGestureDetector;
	public static final int FLING_MIN_DISTANCE = 150;
	public static final int FLING_MIN_VELOCITY = 0;

	public static final String ID_PAIR = "ID_PAIR";
	public static final String NEWEST_ID = "NewestId";
	public static final String OLDEST_ID = "OldestId";
	private long mNewestId = -1;
	private long mOldestId = -1;
	private Count mUnreadCount = null;
	private static final int MAX_GET_EVERY_TIME = 20;
	private static final int MAX_SAVE_COUNT = 120;
	// private float x, y, z,last_x,last_y,last_z;
	// private long lastUpdate;
	
	public static final String TO_THE_BOTTOM = "com.wibo.toWiboListBottom";

	private final BroadcastReceiver mNotificationToBottom = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(TO_THE_BOTTOM)){
				mWeiboListView.setSelection(mWeiboListView.getCount());
			}
		}
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(!mbRunning){

				Log.e(TAG, "stop by not running flag!");
	    		return;
	    	}
			
			switch (msg.what) {
			case GET_TOKEN:
				break;
			case SHOW_WEIBO:
				
				mWeiboListItemAdapter.notifyDataSetChanged();
				
				Log.i(TAG, "get new weibo finished!");
				
				mHeadLayout.setVisibility(RelativeLayout.GONE);
				mProgressBar.setVisibility(ProgressBar.GONE);
				
				Intent intent = new Intent();
				intent.setAction(WiboMainTabActivity.CLEAN_HOME_ACTION);
				sendBroadcast(intent);
				
				sendMessageDelayed2(SHOW_WEIBO_TOP, 50);
				if (msg.obj != null)
					showNewWeiboToast((String)msg.obj);
				break;
				
			case SHOW_WEIBO_TOP:
				mWeiboListView.onRefreshComplete();
				loadImageDrawable(0);
				//mWeiboListView.setSelection(0);
				break;
				
			case SHOW_WEIBO_BUTTOM:
				mFooterPro.setVisibility(ProgressBar.INVISIBLE);
				mProgressBar.setVisibility(ProgressBar.GONE);
				mWeiboListItemAdapter.notifyDataSetChanged();
				//loadImageDrawable();
				break;

			case SHOW_WEIBO_ERROR:
				Log.e(TAG, "get new weibo error!");
				mWeiboListView.onRefreshComplete();
				mProgressBar.setVisibility(ProgressBar.GONE);
				sendMessageDelayed2(SHOW_WEIBO_TOP, 50);
				// mTextView.setText((String)msg.obj);
				break;
			case SHOW_WEIBO_FROM_DATABASE:
				if (msg.obj != null) {
					ArrayList<WeiboItem> itemDataList = (ArrayList<WeiboItem>)msg.obj;
					mItemDataList.clear();
					mItemDataList.addAll(itemDataList);
					mWeiboListItemAdapter.notifyDataSetChanged();
					mHeadLayout.setVisibility(RelativeLayout.GONE);
					mProgressBar.setVisibility(ProgressBar.GONE);
					mWeiboListView.onRefreshComplete();
					loadImageDrawable(0);
				}
				
				break;
			case REFRESH_LIST:
				mWeiboListItemAdapter.notifyDataSetChanged();
				mProgressBar.setVisibility(ProgressBar.GONE);
				//mWeiboListView.setLastUpdated("18:88");
				break;
//			case VERIFY_USER_FINISH:
//				if (msg.obj != null) {
//					User user = (User) msg.obj;
//					mUserManager.setAccountUser(user);
//					mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
//					mUserManager.setUserId(user.getId());
//					setTitle(user.getName());
//					mIsVerify = true;
//					
//					RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainListLayout);
//					ImageView iv = (ImageView) findViewById(R.id.mainLoadingImage);
//					mainLayout.setVisibility(RelativeLayout.VISIBLE);
//					iv.setVisibility(ImageView.GONE);
//					
//					TabActivity parent = (TabActivity)getParent();
//					TabWidget tabwidget = parent.getTabWidget();
//					tabwidget.setVisibility(TabWidget.VISIBLE);
//					mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
//					
//					SharedPreferences settings = getSharedPreferences(USER_INFO, 0);
//					Editor editor = settings.edit();
//					editor.putString(USER_NAME, user.getName());
//					editor.putLong(USER_ID, user.getId());
//					editor.commit();
//				}
//				break;
//			case VERIFY_USER_ERROR:
//				// 清除数据退出
//				mUserManager.setAccountUser(null);
//				mIsVerify = false;
//				SharedPreferences settings = getSharedPreferences(WiboMainLoginActivity.SETTINGS_TOKEN_PAIR, 0);
//				Editor editor = settings.edit();
//				editor.putString(WiboMainLoginActivity.TOKEN, "");
//				editor.putString(WiboMainLoginActivity.TOKEN_SECRET, "");
//				editor.commit();
//				
//				Intent intent = new Intent(WiboMainActivity.this, WiboMainLoginActivity.class);
//				startActivity(intent);
//                finish();
//
//				break;
			}
			
			if (mItemDataList.size() > 0) {
				mLvfooter.setVisibility(View.VISIBLE);
			}
			super.handleMessage(msg);
		}

	};
	
	private void sendMessageDelayed2(int what, int delayMillis) {
		Message msg = mHandler.obtainMessage(what);
		mHandler.sendMessageDelayed(msg, delayMillis);
	}

	private void sendMessage(int what, Object obj) {
		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
	private void setContentViewSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			setContentView(R.layout.mainactivity);
			break;
		case 1:
			setContentView(R.layout.mainactivity_2);
			break;
		default:
			setContentView(R.layout.mainactivity);
			break;
		}
	}
	
	private int getListFooterSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			return R.layout.weibofooter;
		case 1:
			return R.layout.weibofooter_2;
		default:
			return R.layout.weibofooter;
		}
	}

//	private Thread mVerifyUserThread = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mbRunning = true;
		mUserManager = CUserManager.getInstance(this);
		
		setContentViewSkin();
		
		if (mAuthConstant == null)
			mAuthConstant = OAuthConstant.getInstance();

		if (mWeibo == null)
			mWeibo = mAuthConstant.getWeibo();
		
//		mWeibo.setToken(mAuthConstant.getToken(), mAuthConstant
//				.getTokenSecret());
		
		if (mDbHelper == null)
			mDbHelper = new FileDbHelper(this);
		
//		TabActivity parent = (TabActivity)getParent();
//		parent.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
//	              WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		TabWidget tabwidget = parent.getTabWidget();
//		tabwidget.setVisibility(TabWidget.GONE);
		
//		if (!mIsVerify && Utility.isNetworkAvailable(WiboMainActivity.this)) {
//			// 验证用户
//			if (mVerifyUserThread != null) {
//				if (mVerifyUserThread.isAlive()) {
//					mVerifyUserThread.interrupt();
//				}
//				mVerifyUserThread = null;
//			}
//			mVerifyUserThread = new Thread(new Runnable() {
//				
//				@Override
//				public void run() {
//					try {
//						User user = mWeibo.verifyCredentials();
//						if (user != null) {
//							sendMessage(VERIFY_USER_FINISH, user);
//						}else{
//							sendMessage(VERIFY_USER_ERROR, null);
//						}
//						
//					} catch (WeiboException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//						sendMessage(VERIFY_USER_ERROR, null);
//					}
//				}
//			});
//			mVerifyUserThread.start();
//			
//		}else{
//			SharedPreferences settings = getSharedPreferences(USER_INFO, 0);
//			long userId = settings.getLong(USER_ID, -100);
//			mUserManager.setUserId(userId);
//			UserItem userItem = mUserManager.getUserFromDB(mDbHelper, mUserManager.getUserId(), Utility.USER_MYSELF);
//			if (userItem != null) {
//				mUserManager.setUserItem(userItem);
//				mUserManager.setUserId(userItem.getmUserId());
//				setTitle(userItem.getmUserName());
//			}else{
//				finish();
//			}
//			RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainListLayout);
//			ImageView iv = (ImageView) findViewById(R.id.mainLoadingImage);
//			mainLayout.setVisibility(RelativeLayout.VISIBLE);
//			iv.setVisibility(ImageView.GONE);
//			tabwidget.setVisibility(TabWidget.VISIBLE);
//		}
	
		bindWeiboService();

		mProgressBar = (ProgressBar) findViewById(R.id.loadingProgress);

		mWeiboListView = (PullToRefreshListView) findViewById(R.id.weiboListView);
		mWeiboListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				showWeiboItemDialog(arg2-1, arg3);
				return false;
			}
			
		});
		mWeiboListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getParent(), WeiboDetailsActivity.class);
	    		Bundle bundle = new Bundle();
	    		bundle.putLong("weiboId", mItemDataList.get(arg2 - 1).getmWeiboId());
	    		bundle.putSerializable("weiboItem", mItemDataList.get(arg2 - 1));
				intent.putExtras(bundle);
				//intent.setFlags(Intent.);
				getParent().startActivity(intent);
			}
		});
		
		mHeadLayout = (RelativeLayout) findViewById(R.id.headLayout);
		mHeadLayout.setVisibility(RelativeLayout.GONE);

		mItemDataList = new ArrayList<WeiboItem>();
		mWeiboListItemAdapter = new WeiboListItemAdapter(this);

		mWeiboListItemAdapter.setAdapterData(mItemDataList);
		mLvfooter = LayoutInflater.from(WiboMainActivity.this).inflate(getListFooterSkin(), null);	
		
		if(mLvfooter != null){
			mFooterPro = (ProgressBar) mLvfooter.findViewById(R.id.moreWeiboProgress);
			mFooterPro.setVisibility(ProgressBar.INVISIBLE);
			mLvfooter.setVisibility(View.INVISIBLE);

			mWeiboListView.addFooterView(mLvfooter);
			mWeiboListView.setFooterDividersEnabled(true);
			mLvfooter.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//Toast.makeText(WiboMainActivity.this, "~~~~", Toast.LENGTH_SHORT).show();
					if (!Utility.isNetworkAvailable(WiboMainActivity.this)){
						Toast.makeText(WiboMainActivity.this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
						return;
					}
					getMoreWeibo(mItemDataList.get(mItemDataList.size()-1).getmWeiboId());
				}
			});
		}

		mWeiboListView.setAdapter(mWeiboListItemAdapter);
		
		mGestureDetector = new GestureDetector(this);

		mWeiboListView.setOnTouchListener(this);
		mWeiboListView.setLongClickable(true);
		mWeiboListView.setSelected(true);
		mWeiboListView.setOnScrollListener(this);

		if (!Utility.isNetworkAvailable(this)){
			Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
		}

		mWeiboListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                //new GetDataTask().execute();
            	getNewestWeibo();
            }
        });
		getWeiboListToDatabase();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(TO_THE_BOTTOM);
      	registerReceiver(mNotificationToBottom, intentFilter);
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();
		SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
        SharedPreferences.Editor editor = lastPreferences.edit();
        editor.putInt(Constants.PREFERENCE_RECORD, 0);
        editor.commit();
	}

	private boolean bindWeiboService() {
		Intent serviceIntent = new Intent();
		serviceIntent.setAction("com.wibo.service.WeiboService");
		ComponentName name = getApplicationContext().startService(serviceIntent);
		if (name == null) {
			return false;
		}
		boolean isSuc = getApplicationContext().bindService(serviceIntent, mAccountConnection, Context.BIND_AUTO_CREATE);
		
		return isSuc;
	}
	
	private IWeiboService mWeiboService = null;
	
	private ServiceConnection mAccountConnection = new ServiceConnection() {
		
		public void onServiceDisconnected(ComponentName name) {
			mWeiboService = null;
			
		}
		
		public void onServiceConnected(ComponentName name, IBinder service) {
			mWeiboService = IWeiboService.Stub.asInterface(service);
			try{
				mWeiboService.registerCallback(mWeiboServiceCallback);
			}catch(RemoteException e){
				e.printStackTrace();
			}
			
		}
	};
	
	private IWeiboServiceCallback.Stub mWeiboServiceCallback = new IWeiboServiceCallback.Stub() {
		
		@Override
		public void unreadWeibo(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadTransmit(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadFans(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadComment(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void haveNewWeibo(boolean isHave) throws RemoteException {
			if (isHave) {
				
			}
		}

		@Override
		public void unreadTotalMessages(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
	};
//    private class GetDataTask extends AsyncTask<Void, Void, String[]> {
//
////        @Override
////        protected String[] doInBackground(Void... params) {
////            // Simulates a background job.
////            try {
////                Thread.sleep(2000);
////            } catch (InterruptedException e) {
////                ;
////            }
////            return mStrings;
////        }
//
//        @Override
//        protected void onPostExecute(String[] result) {
//            //mListItems.addFirst("Added after refresh...");
//
//            // Call onRefreshComplete when the list has been refreshed.
//            mWeiboListView.onRefreshComplete();
//
//            super.onPostExecute(result);
//        }
//
//		@Override
//		protected String[] doInBackground(Void... params) {
//			getNewestWeibo();
//			return null;
//		}
//    }
	
	@Override
	public void onBackPressed() {
        Activity parent = getParent();
        if(parent != null) {
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 0);
            editor.commit();
            
            parent.onBackPressed();
        } else {       	
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 0);
            editor.commit();
            
            super.onBackPressed();
        }
	}

	@Override
	protected void onPause() {
		Activity parent = getParent();
        if(parent != null) {
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 0);
            editor.commit();
            
        } else {       	
        	SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
            SharedPreferences.Editor editor = lastPreferences.edit();
            editor.putInt(Constants.PREFERENCE_RECORD, 0);
            editor.commit();
            
        }
		super.onPause();
	}

	private void showWeiboItemDialog(final int pos, long id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(WiboMainActivity.this);
		builder.setTitle(R.string.weiboOperation);
		builder.setItems(R.array.weiboItem_ary, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
            	switch (which) {
            	case 0:
            		Intent intent = new Intent(WiboMainActivity.this, SendWeiboActivity.class);
            		Bundle bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.REPLY_COMMENT);
            		bundle.putLong("weiboId", mItemDataList.get(pos).getmWeiboId());
            		bundle.putString("username", mItemDataList.get(pos).getmUserName());
            		bundle.putString("text", mItemDataList.get(pos).getmWeiboText());

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	case 1:
            		intent = new Intent(WiboMainActivity.this, SendWeiboActivity.class);
            		bundle = new Bundle();
            		bundle.putInt(SendWeiboActivity.SEND_WEIBO_TYPE, SendWeiboActivity.TRANSMIT_WEIBO);
            		bundle.putLong("weiboId", mItemDataList.get(pos).getmWeiboId());
            		bundle.putString("username", mItemDataList.get(pos).getmUserName());
            		bundle.putString("text", mItemDataList.get(pos).getmWeiboText());
            		if (mItemDataList.get(pos).getmRtrootText() != null){
            			bundle.putString("rootText", mItemDataList.get(pos).getmRtrootText());
            			bundle.putString("rootUsername", mItemDataList.get(pos).getmRtrootUsername());
            		}

					intent.putExtras(bundle);
					startActivity(intent);
            		break;
            	case 2:
            		break;
            	case 3:
            		ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            		//clip.getText();    // 粘贴
            		clip.setText(mItemDataList.get(pos).getmWeiboText());
            		Toast.makeText(WiboMainActivity.this, getString(R.string.copySuc), Toast.LENGTH_SHORT).show();
            		break;
            	case 4:
            		intent = new Intent(WiboMainActivity.this, WiboUserDetailsActivity.class);
        			bundle = new Bundle();
            		bundle.putLong("userId", mItemDataList.get(pos).getmUserId());
            		intent.putExtras(bundle);
        			startActivity(intent);
            		
            		break;
            	}
            	
			}
		});
		
		builder.show();
	}
	
	

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		if (e1 == null || e2 == null) {
			return false;
		}
		
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {

			// 切换Activity
//			Intent intent = new Intent(WiboMainActivity.this,
//			WiboTabActivity.class);
//			startActivity(intent);
			((TabActivity)getParent()).getTabHost().setCurrentTab(1);
//			WiboMainTabActivity instance = WiboMainTabActivity.getMainTabInstance(WiboMainActivity.this);
//			instance.setTab(1);
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY && Math.abs(e2.getY() - e1.getY()) < 30) {

			if (!Utility.isNetworkAvailable(WiboMainActivity.this)){
				Toast.makeText(WiboMainActivity.this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
				return false;
			}
			
			// 切换Activity
			Intent intent = new Intent(WiboMainActivity.this,
					SendWeiboActivity.class);
			startActivity(intent);
		} /*else if (mWeiboListView.getSelectedItemPosition() < 1 && e2.getY() - e1.getY() > 150
				&& Math.abs(velocityY) > FLING_MIN_VELOCITY && Math.abs(e2.getX() - e1.getX()) < 30) {
			if (!Utility.isNetworkAvailable(this)){
				Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
				return false;
			}
			
			getNewestWeibo();
		}*/

		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return mGestureDetector.onTouchEvent(event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if (mNewestThread != null) {
			if (mNewestThread.isAlive()) {
				mNewestThread.interrupt();
			}
			mNewestThread = null;
		}
		
		if (mGetPicThread != null) {
			if (mGetPicThread.isAlive()) {
				mGetPicThread.interrupt();
			}
			mGetPicThread = null;
		}
		
		if (mMoreWeiboThread != null) {
			if (mMoreWeiboThread.isAlive()) {
				mMoreWeiboThread.interrupt();
			}
			mMoreWeiboThread = null;
			isGettingMoreWeibo = false;
		}
		
		if (mThreadGetFromDatabase != null) {
			if (mThreadGetFromDatabase.isAlive()) {
				mThreadGetFromDatabase.interrupt();
			}
			mThreadGetFromDatabase = null;
		}
		
		if(mWeiboService != null){
			try{
				getApplicationContext().unbindService(mAccountConnection);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				mWeiboService = null;
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, getString(R.string.refreshWeibo))/*.setIcon(
				R.drawable.ic_menu_edit_password)*/;
		menu.add(0, 1, 1, getString(R.string.newWeibo))/*.setIcon(
				R.drawable.ic_menu_exit)*/;
		menu.add(0, 2, 2, getString(R.string.chargeSkin))/*.setIcon(
				R.drawable.ic_menu_exit)*/;
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case 0:
			if (!Utility.isNetworkAvailable(this)){
				Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
				return false;
			}
			mProgressBar.setVisibility(ProgressBar.VISIBLE);
			getNewestWeibo();
			break;
		case 1:
			if (!Utility.isNetworkAvailable(this)){
				Toast.makeText(this, getString(R.string.networkFail), Toast.LENGTH_SHORT).show();
				return false;
			}
			
			Intent intent = new Intent(WiboMainActivity.this,
					SendWeiboActivity.class);
			startActivity(intent);
			break;
		case 2:
//			int currentSkin = mUserManager.getMySkin();
//			if (currentSkin == 1){
//				mUserManager.setMySkin(0);
//			}else{
//				mUserManager.setMySkin(1);
//			}
			intent = new Intent(WiboMainActivity.this, com.wibo.account.WiboSettings.class);
			startActivity(intent);
			
			break;
		}
		return false;
	}

	private void showNewWeiboToast(String weiboCount) {
		Toast.makeText(WiboMainActivity.this, weiboCount + getString(R.string.newWeiboCount), Toast.LENGTH_SHORT).show();
	}
	
	private Thread mGetPicThread = null;
	
	public static final int DOWNLOAD_IMAGE_MAX_SIZE = 5;
	
	public void loadImageDrawable(final int startIndex) {
		if(startIndex < mItemDataList.size() ){
			
			int lastIndex = mItemDataList.size() - 1;
			if(lastIndex - startIndex > DOWNLOAD_IMAGE_MAX_SIZE) {
				lastIndex = startIndex + DOWNLOAD_IMAGE_MAX_SIZE;
			}
			loadWeiboPic(startIndex, lastIndex);
		}
	}
	
	private void loadWeiboPic(final int startIndex, final int lastIndex) {
		
		if (mGetPicThread != null) {
			if (mGetPicThread.isAlive()) {
				mGetPicThread.interrupt();
			}
			mGetPicThread = null;
		}
		
		mGetPicThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				//isGetPic = true;
				
				Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
				int size = mItemDataList.size();
				String path = null;
				for (int i = startIndex; lastIndex < size && i <= lastIndex; i++) {
					path = Utility.getImagePath(WiboMainActivity.this, mItemDataList.get(i).getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC);
					if (path != null) {
						mItemDataList.get(i).setmIsLoadHeadPic(true);
					}
										
					if (mItemDataList.get(i).getmWeiboPic() != null && !mItemDataList.get(i).getmWeiboPic().isEmpty()){
						path = Utility.getImagePath(WiboMainActivity.this, mItemDataList.get(i).getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC);
						if (path != null) {
							mItemDataList.get(i).setmIsLoadWeiboPic(true);
						}
					}
					
					if (mItemDataList.get(i).getmRtrootText() != null && !mItemDataList.get(i).getmRtrootText().isEmpty()) {
						if (mItemDataList.get(i).getmRtrootWeiboPic() != null && !mItemDataList.get(i).getmRtrootWeiboPic().isEmpty()){
							path = Utility.getImagePath(WiboMainActivity.this, mItemDataList.get(i).getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC);
							if (path != null) {
								mItemDataList.get(i).setmIsLoadRootPic(true);
							}
						}
					}
					
					
					sendMessage(REFRESH_LIST, null);
				}
				//isGetPic = false;
			}
		});
		
		//if (!isGetPic) {
			mGetPicThread.start();
		//}
	}

	private Thread mNewestThread = null;
	private static boolean isGettingNewestWeibo = false;
	public static final int GET_COUNT_MAX = 100;

	public void getNewestWeibo() {
		if (mNewestThread != null) {
			if (mNewestThread.isAlive()) {
				mNewestThread.interrupt();
			}
			mNewestThread = null;
			isGettingNewestWeibo = false;
		}
		
		Log.i(TAG, "get new weibo started!");
		mNewestThread = new Thread(new Runnable() {

			@Override
			public void run() {
				isGettingNewestWeibo = true;
				try {

					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_WEIBO_ERROR, null);
							return;
						}
					}
					List<Status> statuses = null;
					// 获取前20条关注用户的微博信息
					statuses = mWeibo.getFriendsTimeline();

					if (statuses.size() > 0) {
						// 保存第一条和最后一条微博的ID
						long newestId = statuses.get(0).getId();
						long the20thId = statuses.get(statuses.size() - 1)
								.getId();

						ArrayList<WeiboItem> itemDataList = new ArrayList<WeiboItem>();

						if (mNewestId == -1 || (mNewestId < newestId && the20thId < mNewestId)) {
							boolean isInclude = false;
							// 新的20条完全包含了旧的
							if (mOldestId > the20thId) {
								isInclude = true;
							}

							for (Status status : statuses) {
								if (status.getId() == mNewestId && !isInclude) {
									break;
								}
								WeiboItem itemData = new WeiboItem();
								itemData.setmUserName(status.getUser()
										.getName());
								itemData.setmSentTime(Utility.formatDate(status
										.getCreatedAt()));
								itemData.setmWeiboText(status.getText());
								itemData.setmClientName(status.getSource());
								itemData.setmWeiboUserPic(status.getUser()
										.getProfileImageURL().toString());
								if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
									itemData.setmWeiboPic(status.getThumbnail_pic());
									itemData.setmWeiboMidPic(status.getBmiddle_pic());
									itemData.setmWeiboLargePic(status.getOriginal_pic());
								}

								itemData.setmUserId(status.getUser().getId());
								itemData.setmVLogo(status.getUser().isVerified());
								itemData.setmLatitude(String.valueOf(status.getLatitude()));
								itemData.setmLongitude(String.valueOf(status.getLongitude()));
								
								Status transmitStatus = status.getRetweeted_status();
								if (transmitStatus != null) {
									itemData.setmRtrootText(transmitStatus.getText());
									itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
									itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
									itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
									itemData.setmRtrootWeiboId(transmitStatus.getId());
									itemData.setmRtrootUsername(transmitStatus.getUser().getName());
									itemData.setmRtrootUserId(transmitStatus.getUser().getId());
									itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
								}
								itemData.setmWeiboId(status.getId());

								if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
									itemData.setmIsLoadHeadPic(true);
								}
								
								if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
									if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadWeiboPic(true);
									}
								}
								
								if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
									if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
										if (Utility.isImageExist(WiboMainActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
											itemData.setmIsLoadRootPic(true);
										}
									}
								}
								
								itemDataList.add(itemData);
							}

							if (isInclude) {
								mItemDataList.clear();
								mItemDataList.addAll(itemDataList);
								
							} else {
								// 超过60条删除旧的
								int totalSize = mItemDataList.size()
										+ itemDataList.size();
								int originalCount = mItemDataList.size();
								if (totalSize > MAX_SAVE_COUNT) {
									for (int i = originalCount - 1; i > originalCount - (totalSize - MAX_SAVE_COUNT) - 1; i--) {
										mItemDataList.remove(i);
									}
									mItemDataList.addAll(0, itemDataList);
								} else {
									mItemDataList.addAll(0, itemDataList);
								}
							}
							mNewestId = mItemDataList.get(0).getmWeiboId();
							mOldestId = mItemDataList.get(mItemDataList.size() - 1).getmWeiboId();
						} else if (mNewestId < newestId
								&& mNewestId < the20thId) {
							for (Status status : statuses) {
								WeiboItem itemData = new WeiboItem();
								itemData.setmUserName(status.getUser()
										.getName());
								itemData.setmSentTime(Utility.formatDate(status
										.getCreatedAt()));
								itemData.setmWeiboText(status.getText());
								itemData.setmClientName(status.getSource());
								itemData.setmWeiboUserPic(status.getUser()
										.getProfileImageURL().toString());
								if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
									itemData.setmWeiboPic(status.getThumbnail_pic());
									itemData.setmWeiboMidPic(status.getBmiddle_pic());
									itemData.setmWeiboLargePic(status.getOriginal_pic());
								}

								itemData.setmUserId(status.getUser().getId());
								itemData.setmVLogo(status.getUser().isVerified());
								itemData.setmLatitude(String.valueOf(status.getLatitude()));
								itemData.setmLongitude(String.valueOf(status.getLongitude()));
								
								Status transmitStatus = status.getRetweeted_status();
								if (transmitStatus != null) {
									itemData.setmRtrootText(transmitStatus.getText());
									itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
									itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
									itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
									itemData.setmRtrootWeiboId(transmitStatus.getId());
									itemData.setmRtrootUsername(transmitStatus.getUser().getName());
									itemData.setmRtrootUserId(transmitStatus.getUser().getId());
									itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
								}
								itemData.setmWeiboId(status.getId());
								itemDataList.add(itemData);
							} 
							mItemDataList.clear();
							mItemDataList.addAll(itemDataList);
							mNewestId = mItemDataList.get(0).getmWeiboId();
							mOldestId = mItemDataList.get(mItemDataList.size() - 1).getmWeiboId();
														
						}
						if (itemDataList.size() > 0){
							sendMessage(SHOW_WEIBO, String.valueOf(itemDataList.size()));
						}
						else
							sendMessage(SHOW_WEIBO, null);
						
						// 获取评论和转发数
						int leftSize = mItemDataList.size();
						List<Count> counts = null;
						int i = 0;
						int j = 0;
						int startIndex = 0;
						String ids = "";
						if (leftSize > GET_COUNT_MAX) {
							do {
								for (; i < startIndex + GET_COUNT_MAX; i++) {
									ids += String.valueOf(mItemDataList.get(i).getmWeiboId()) + ",";
								}
								ids = ids.substring(0, ids.length() - 1);

								counts = mWeibo.getCounts(ids);
								
								if (counts != null) {
									for (Count count : counts) {
										for (j = 0; j < mItemDataList.size(); j++) {
											if (mItemDataList.get(j).getmWeiboId() == count.getId()){
												mItemDataList.get(j).setmCommentCount(String.valueOf(count.getComments()));
												mItemDataList.get(j).setmTransmitCount(String.valueOf(count.getRt()));
												break;
											}
										}
									}
								}
								startIndex += GET_COUNT_MAX;
							} while ((leftSize -= GET_COUNT_MAX) > GET_COUNT_MAX);
						}
						
						if (leftSize > 0 && leftSize <= GET_COUNT_MAX) {
							ids = "";
							for (; i < mItemDataList.size(); i++) {
								ids += String.valueOf(mItemDataList.get(i).getmWeiboId()) + ",";
							}
							ids = ids.substring(0, ids.length() - 1);

							counts = mWeibo.getCounts(ids);
							
							if (counts != null) {
								for (Count count : counts) {									
									for (j = 0; j < mItemDataList.size(); j++) {
										if (mItemDataList.get(j).getmWeiboId() == count.getId()){
											mItemDataList.get(j).setmCommentCount(String.valueOf(count.getComments()));
											mItemDataList.get(j).setmTransmitCount(String.valueOf(count.getRt()));
											break;
										}
									}
								}
							}
						}
						
						sendMessage(REFRESH_LIST, null);
						
						addWeiboListToDatabase();
					}
				} catch (WeiboException e) {
					sendMessage(SHOW_WEIBO_ERROR, e.getMessage());
					e.printStackTrace();
				} finally {
					isGettingNewestWeibo = false;
				}
			}
		});
		
		if (!isGettingNewestWeibo && !isGettingFromDatabase && !isGettingMoreWeibo){
			mNewestThread.start();
		}
		
	}
	
	private Thread mMoreWeiboThread = null;
	private static boolean isGettingMoreWeibo = false;
	
	private void getMoreWeibo(final long lastId) {
		if (mMoreWeiboThread != null) {
			if (mMoreWeiboThread.isAlive()) {
				mMoreWeiboThread.interrupt();
			}
			mMoreWeiboThread = null;
			isGettingMoreWeibo = false;
		}
		mMoreWeiboThread = new Thread(new Runnable() {
			
			@Override
			public synchronized void run() {
				isGettingMoreWeibo = true;
				try {
					if (mUserManager.getAccountUser() == null) {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							mUserManager.setAccountUser(user);
							mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
							mUserManager.setUserId(user.getId());
						}else{
							sendMessage(SHOW_WEIBO_ERROR, null);
							return;
						}
					}
					
					Paging paging = new Paging(1, 20);
					paging.setMaxId(lastId - 1);
					List<Status> statuses = null;
					statuses = mWeibo.getFriendsTimeline(paging);
					
					if (statuses != null && statuses.size() > 0) {
						// 保存第一条和最后一条微博的ID
						long newestId_2 = statuses.get(0).getId();
						long the20thId_2 = statuses.get(statuses.size() - 1)
								.getId();
						ArrayList<WeiboItem> itemDataList = new ArrayList<WeiboItem>();
						
						for (Status status : statuses) {
							WeiboItem itemData = new WeiboItem();
							itemData.setmUserName(status.getUser()
									.getName());
							itemData.setmSentTime(Utility.formatDate(status
									.getCreatedAt()));
							itemData.setmWeiboText(status.getText());
							itemData.setmClientName(status.getSource());

							itemData.setmWeiboUserPic(status.getUser()
									.getProfileImageURL().toString());
							if (status.getThumbnail_pic() != null && !status.getThumbnail_pic().isEmpty()){
								itemData.setmWeiboPic(status.getThumbnail_pic());
								itemData.setmWeiboMidPic(status.getBmiddle_pic());
								itemData.setmWeiboLargePic(status.getOriginal_pic());
							}

							itemData.setmUserId(status.getUser().getId());
							itemData.setmVLogo(status.getUser().isVerified());
							itemData.setmLatitude(String.valueOf(status.getLatitude()));
							itemData.setmLongitude(String.valueOf(status.getLongitude()));
							
							Status transmitStatus = status.getRetweeted_status();
							if (transmitStatus != null) {
								itemData.setmRtrootText(transmitStatus.getText());
								itemData.setmRtrootWeiboPic(transmitStatus.getThumbnail_pic());
								itemData.setmRtrootWeiboMidPic(transmitStatus.getBmiddle_pic());
								itemData.setmRtrootWeiboLargePic(transmitStatus.getOriginal_pic());
								itemData.setmRtrootWeiboId(transmitStatus.getId());
								itemData.setmRtrootUsername(transmitStatus.getUser().getName());
								itemData.setmRtrootUserId(transmitStatus.getUser().getId());
								itemData.setmRtrootVLogo(transmitStatus.getUser().isVerified());
							}
							itemData.setmWeiboId(status.getId());
							
							if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
								itemData.setmIsLoadHeadPic(true);
							}
							
							if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
								if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
									itemData.setmIsLoadWeiboPic(true);
								}
							}
							
							if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
								if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
									if (Utility.isImageExist(WiboMainActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
										itemData.setmIsLoadRootPic(true);
									}
								}
							}
							
							itemDataList.add(itemData);
						}
						
						if (itemDataList.size() > 0) {
							mItemDataList.addAll(itemDataList);
							mNewestId = mItemDataList.get(0).getmWeiboId();
							mOldestId = mItemDataList.get(
									mItemDataList.size() - 1).getmWeiboId();
							
							sendMessage(SHOW_WEIBO_BUTTOM, String.valueOf(itemDataList.size()));
						}else{
							sendMessage(SHOW_WEIBO_BUTTOM, null);
						}
						
						// 获取评论和转发数
						int leftSize = mItemDataList.size();
						List<Count> counts = null;
						int i = 0;
						int j = 0;
						int startIndex = 0;
						String ids = "";
						if (leftSize > GET_COUNT_MAX) {
							do {
								for (; i < startIndex + GET_COUNT_MAX; i++) {
									ids += String.valueOf(mItemDataList.get(i).getmWeiboId()) + ",";
								}
								ids = ids.substring(0, ids.length() - 1);

								counts = mWeibo.getCounts(ids);
								
								if (counts != null) {
									for (Count count : counts) {
										for (j = 0; j < mItemDataList.size(); j++) {
											if (mItemDataList.get(j).getmWeiboId() == count.getId()){
												mItemDataList.get(j).setmCommentCount(String.valueOf(count.getComments()));
												mItemDataList.get(j).setmTransmitCount(String.valueOf(count.getRt()));
												break;
											}
										}
									}
								}
								startIndex += GET_COUNT_MAX;
							} while ((leftSize -= GET_COUNT_MAX) > GET_COUNT_MAX);
						}
						
						if (leftSize > 0 && leftSize <= GET_COUNT_MAX) {
							ids = "";
							for (; i < mItemDataList.size(); i++) {
								ids += String.valueOf(mItemDataList.get(i).getmWeiboId()) + ",";
							}
							ids = ids.substring(0, ids.length() - 1);

							counts = mWeibo.getCounts(ids);
							
							if (counts != null) {
								for (Count count : counts) {									
									for (j = 0; j < mItemDataList.size(); j++) {
										if (mItemDataList.get(j).getmWeiboId() == count.getId()){
											mItemDataList.get(j).setmCommentCount(String.valueOf(count.getComments()));
											mItemDataList.get(j).setmTransmitCount(String.valueOf(count.getRt()));
											break;
										}
									}
								}
							}
						}
						
						sendMessage(REFRESH_LIST, null);
						
						addWeiboListToDatabase();
					}
				} catch (WeiboException e) {
					sendMessage(SHOW_WEIBO_ERROR, e.getMessage());
					e.printStackTrace();
				} finally {
					isGettingMoreWeibo = false;
				}
			}
		});
		if (!isGettingMoreWeibo && !isGettingFromDatabase && !isGettingNewestWeibo) {
			mFooterPro.setVisibility(ProgressBar.VISIBLE);
			mMoreWeiboThread.start();
		}
		
	}
	


	private void addWeiboListToDatabase() {
		try {
			mDbHelper.open();
			mDbHelper.deleteAllWeiboListData();
			//int count = mItemDataList.size() > 60 ? 60 : mItemDataList.size();
			int i = 0;
			for (/*int i = count - 1*/; /*i >= 0*/i < mItemDataList.size() && i < MAX_SAVE_COUNT; i++) {
				HashMap<String, Object> hashMap = new HashMap<String, Object>();
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_ID, mItemDataList
						.get(i).getmWeiboId());
				hashMap.put(FileDbHelper.WEIBO_LIST_USER_PIC, mItemDataList
						.get(i).getmWeiboUserPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_PIC, mItemDataList
						.get(i).getmWeiboPic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_MID_PIC, mItemDataList
						.get(i).getmWeiboMidPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_LARGE_PIC, mItemDataList
						.get(i).getmWeiboLargePic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_ORIGINAL_WEIBO_PIC,
						mItemDataList.get(i).getmRtrootWeiboPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_MID_PIC, mItemDataList
						.get(i).getmRtrootWeiboMidPic());
				hashMap.put(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_LARGE_PIC, mItemDataList
						.get(i).getmRtrootWeiboLargePic());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_USERNAME, mItemDataList
						.get(i).getmUserName());
				hashMap.put(FileDbHelper.WEIBO_LIST_WEIBO_TEXT, mItemDataList
						.get(i).getmWeiboText());
				hashMap.put(FileDbHelper.WEIBO_LIST_ORIGINAL_TEXT,
						mItemDataList.get(i).getmRtrootText());
				hashMap.put(FileDbHelper.WEIBO_LIST_SENT_TIME, mItemDataList
						.get(i).getmSentTime());
				hashMap.put(FileDbHelper.WEIBO_LIST_CLIENT_NAME, mItemDataList
						.get(i).getmClientName());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_USER_ID, mItemDataList
						.get(i).getmUserId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_USERNAME, mItemDataList
						.get(i).getmRtrootUsername());
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_WEIBO_ID, mItemDataList
						.get(i).getmRtrootWeiboId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_VIP, mItemDataList
						.get(i).ismVLogo() ? "true" : "false");
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_UID, mItemDataList
						.get(i).getmRtrootUserId());
				
				hashMap.put(FileDbHelper.WEIBO_LIST_RTROOT_VIP, mItemDataList
						.get(i).ismRtrootVLogo() ? "true" : "false");
				
				hashMap.put(FileDbHelper.WEIBO_LIST_LONGITUDE, mItemDataList
						.get(i).getmLongitude());
				hashMap.put(FileDbHelper.WEIBO_LIST_LATITUDE, mItemDataList
						.get(i).getmLatitude());
				hashMap.put(FileDbHelper.WEIBO_LIST_ADD_DATA1, FileDbHelper.MY_WEIBO_LIST);

				hashMap.put(FileDbHelper.WEIBO_LIST_COMMENT_COUNT,
						mItemDataList.get(i).getmCommentCount());
				hashMap.put(FileDbHelper.WEIBO_LIST_TRANSMIT_COUNT,
						mItemDataList.get(i).getmTransmitCount());
				mDbHelper.insertWeiboListData(hashMap);
			}
			SharedPreferences settings = getSharedPreferences(ID_PAIR, 0);
			Editor editor = settings.edit();
			editor.putLong(NEWEST_ID, mNewestId);
			editor.putLong(OLDEST_ID, mItemDataList.get(i-1).getmWeiboId());
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mDbHelper.close();
		}
	}

	private Thread mThreadGetFromDatabase = null;
	private static boolean isGettingFromDatabase = false;
	
	private void getWeiboListToDatabase() {
		mThreadGetFromDatabase = new Thread(new Runnable() {
			
			@Override
			public void run() {
				isGettingFromDatabase = true;
				try {
					mDbHelper.open();
					
					Cursor weiboListCursor = mDbHelper.getAllWeiboListData();

					final int weib_id = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_ID);
					final int user_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_PIC);
					final int weibo_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_PIC);
					final int weibo_mid_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_MID_PIC);
					final int weibo_large_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_LARGE_PIC);
					final int original_weibo_pic = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_WEIBO_PIC);
					final int root_weibo_mid_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_MID_PIC);
					final int root_weibo_large_pic = weiboListCursor
					.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ROOT_WEIBO_LARGE_PIC);
					final int username = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USERNAME);
					final int weibo_text = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_TEXT);
					final int original_text = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ORIGINAL_TEXT);
					final int sent_time = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_SENT_TIME);
					final int client_name = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_CLIENT_NAME);
					final int comment_count = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_COMMENT_COUNT);
					final int transmit_count = weiboListCursor
							.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_TRANSMIT_COUNT);
					
					final int user_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USER_ID);
					final int root_username = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_USERNAME);
					final int root_weibo_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_WEIBO_ID);
					final int user_vip = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_VIP);
					final int root_user_id = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_UID);
					final int root_user_vip = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_RTROOT_VIP);
					final int longitude = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LONGITUDE);
					final int latitude = weiboListCursor
						.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_LATITUDE);
					
					final int add_data1 = weiboListCursor.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_ADD_DATA1);
					
					//weiboListCursor.moveToFirst();
					weiboListCursor.moveToLast();
					ArrayList<WeiboItem> itemDataList = new ArrayList<WeiboItem>();
					//for (int i = 0; i < weiboListCursor.getCount(); i++) {
					for (int i = weiboListCursor.getCount() - 1; i >= 0; i--) {
						WeiboItem itemData = new WeiboItem();
						if (weiboListCursor.getLong(add_data1) != FileDbHelper.MY_WEIBO_LIST) {
							weiboListCursor.moveToPrevious();
							continue;
						}
						itemData.setmWeiboId(weiboListCursor.getLong(weib_id));
						itemData.setmWeiboUserPic(weiboListCursor.getString(user_pic));
						itemData.setmWeiboPic(weiboListCursor.getString(weibo_pic));
						itemData.setmWeiboMidPic(weiboListCursor.getString(weibo_mid_pic));
						itemData.setmWeiboLargePic(weiboListCursor.getString(weibo_large_pic));
						itemData.setmRtrootWeiboPic(weiboListCursor
								.getString(original_weibo_pic));
						itemData.setmRtrootWeiboMidPic(weiboListCursor.getString(root_weibo_mid_pic));
						itemData.setmRtrootWeiboLargePic(weiboListCursor.getString(root_weibo_large_pic));
						itemData.setmUserName(weiboListCursor.getString(username));
						itemData.setmWeiboText(weiboListCursor.getString(weibo_text));
						itemData.setmRtrootText(weiboListCursor
								.getString(original_text));
						itemData.setmSentTime(weiboListCursor.getString(sent_time));
						itemData.setmClientName(weiboListCursor.getString(client_name));
						itemData.setmCommentCount(weiboListCursor
								.getString(comment_count));
						itemData.setmTransmitCount(weiboListCursor
								.getString(transmit_count));
						itemData.setmUserId(weiboListCursor.getLong(user_id));
						itemData.setmRtrootUsername(weiboListCursor.getString(root_username));
						itemData.setmRtrootWeiboId(weiboListCursor.getLong(root_weibo_id));
						itemData.setmVLogo(weiboListCursor.getString(user_vip).equalsIgnoreCase("true"));
						itemData.setmRtrootUserId(weiboListCursor.getLong(root_user_id));
						itemData.setmRtrootVLogo(weiboListCursor.getString(root_user_vip).equalsIgnoreCase("true"));
						itemData.setmLongitude(weiboListCursor.getString(longitude));
						itemData.setmLatitude(weiboListCursor.getString(latitude));
						
						if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboUserPic(), Utility.WEIBO_PIC, Utility.USER_PIC)) {
							itemData.setmIsLoadHeadPic(true);
						}
						
						if (itemData.getmWeiboPic() != null && !itemData.getmWeiboPic().isEmpty()){
							if (Utility.isImageExist(WiboMainActivity.this, itemData.getmWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
								itemData.setmIsLoadWeiboPic(true);
							}
						}
						
						if (itemData.getmRtrootText() != null && !itemData.getmRtrootText().isEmpty()) {
							if (itemData.getmRtrootWeiboPic() != null && !itemData.getmRtrootWeiboPic().isEmpty()){
								if (Utility.isImageExist(WiboMainActivity.this, itemData.getmRtrootWeiboPic(), Utility.WEIBO_PIC, Utility.THUMBNAIL_PIC)) {
									itemData.setmIsLoadRootPic(true);
								}
							}
						}
						
						itemDataList.add(itemData);
						//weiboListCursor.moveToNext();
						weiboListCursor.moveToPrevious();
					}
					weiboListCursor.close();
					if (itemDataList.size() > 0){
						SharedPreferences settings = getSharedPreferences(ID_PAIR, 0);
			        
			        	mNewestId = settings.getLong(NEWEST_ID, -1);
			        	mOldestId = settings.getLong(OLDEST_ID, -1);
			        	
//			        	mItemDataList.clear();
//			        	mItemDataList.addAll(itemDataList);
//			        	
						sendMessage(SHOW_WEIBO_FROM_DATABASE, itemDataList);
					}else{
						isGettingFromDatabase = false;
						if (Utility.isNetworkAvailable(WiboMainActivity.this))
							getNewestWeibo();
					}
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mDbHelper.close();
					isGettingFromDatabase = false;
				}
			}
		});
		
		
		if (!isGettingMoreWeibo && !isGettingFromDatabase && !isGettingNewestWeibo) {
			//mHeadLayout.setVisibility(RelativeLayout.VISIBLE);
			mThreadGetFromDatabase.start();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		
		}
	}



	// 图片类型
//	public static final int USER_PIC = 0;
//	public static final int THUMBNAIL_PIC = 1;
//	public static final int MIDDLE_PIC = 2;


	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// if (e1.getX()-e2.getX() > SnsConstant.getFlingMinDistance()
		// && Math.abs(distanceX) > SnsConstant.getFlingMinVelocity()) {
		// // Intent intent = new Intent(ViewSnsActivity.this,
		// UpdateStatusActivity.class);
		// // startActivity(intent);
		// } else if (e2.getX()-e1.getX() > SnsConstant.getFlingMinDistance()
		// && Math.abs(distanceX) > SnsConstant.getFlingMinVelocity()) {
		// Intent intent = new Intent(WiboMainActivity.this,
		// SendWeiboActivity.class);
		// startActivity(intent);
		// }

		return false;
	}
	
	// 记录上次获取图片信息的时间
	private int mLastFreshImageIndex = 0;
	
	
	private void refreshImageForList(int viewId){
		if(mItemDataList != null && mItemDataList.size() > 0){
			int startIndex = mWeiboListView.getFirstVisiblePosition();
			int endIndex = mWeiboListView.getLastVisiblePosition();
			
			// 设置上一次的刷新位置
			mLastFreshImageIndex = startIndex;
			
			if(startIndex > 0){
				--startIndex;
			}
			if(endIndex >= mItemDataList.size()){
				endIndex = mItemDataList.size() - 1;
			}
			
			for (int i = startIndex; i <= endIndex; i++) {
				if (!mItemDataList.get(i).ismIsLoadHeadPic() || 
						(mItemDataList.get(i).getmWeiboPic() != null && !mItemDataList.get(i).ismIsLoadWeiboPic()) ||
						(mItemDataList.get(i).getmRtrootWeiboPic() != null && !mItemDataList.get(i).ismIsLoadRootPic())){
					loadWeiboPic(startIndex, endIndex);
					return;
				}
			}
		}
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if(Math.abs(firstVisibleItem - mLastFreshImageIndex) >= DOWNLOAD_IMAGE_MAX_SIZE){
			refreshImageForList(view.getId());
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(scrollState == SCROLL_STATE_IDLE){
			refreshImageForList(view.getId());
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		switch (arg1.getId()) {
		case R.id.weiboListView:
			Intent intent = new Intent(WiboMainActivity.this, WeiboDetailsActivity.class);
    		Bundle bundle = new Bundle();
    		bundle.putLong("weiboId", mItemDataList.get(arg2).getmWeiboId());

			intent.putExtras(bundle);
			startActivity(intent);
			break;
		}
	}
}
